/*
 *所有关于PurchaseReturn类的业务代码应在此处编写
*可使用repository.调用常用方法，获取EF/Dapper等信息
*如果需要事务请使用repository.DbContextBeginTransaction
*也可使用DBServerProvider.手动获取数据库相关信息
*用户信息、权限、角色等使用UserContext.Current操作
*PurchaseReturnService对增、删、改查、导入、导出、审核业务代码扩展参照ServiceFunFilter
*/
using VOL.Core.BaseProvider;
using VOL.Core.Extensions.AutofacManager;
using VOL.Entity.DomainModels;
using System.Linq;
using VOL.Core.Utilities;
using System.Linq.Expressions;
using VOL.Core.Extensions;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Http;
using VOL.Domain.IRepositories;
using VOL.Domain.Infrastructure;
using VOL.Domain.Dto;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http.HttpResults;

namespace VOL.Domain.Services
{
    public partial class PurchaseReturnService
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly IBaseRepository<PurchaseReturn> _purchaseReturnbaseRepository;
        private readonly IPurchaseReturnRepository _repository;//访问数据库

        [ActivatorUtilitiesConstructor]
        public PurchaseReturnService(
            IPurchaseReturnRepository dbRepository,
            IHttpContextAccessor httpContextAccessor,
            IBaseRepository<PurchaseReturn> purchaseReturnbaseRepository
            )
        : base(dbRepository)
        {
            _httpContextAccessor = httpContextAccessor;
            this._purchaseReturnbaseRepository = purchaseReturnbaseRepository;
            _repository = dbRepository;
            //多租户会用到这init代码，其他情况可以不用
            //base.Init(dbRepository);
        }
        public PageGridData<PurchaseReturn> GetPurchaseReturns(GetPurchaseReturnsDto dto)
        {

            // 创建查询条件 - 使用方法链优化代码结构
            var query = _purchaseReturnbaseRepository.GetAll()
                .WhereIF(!string.IsNullOrEmpty(dto.ReturnCode),
                        x => x.ReturnCode.Contains(dto.ReturnCode))
                .WhereIF(!string.IsNullOrEmpty(dto.ReturnName),
                        x => x.ReturnName.Contains(dto.ReturnName))
                .WhereIF(!string.IsNullOrEmpty(dto.PurchaseCode),
                        x => x.PurchaseCode.Contains(dto.PurchaseCode))
                .WhereIF(!string.IsNullOrEmpty(dto.SupplierName),
                        x => x.SupplierName.Contains(dto.SupplierName));

            var totalCount = query.Count();
            var result = new PageGridData<PurchaseReturn> { total = totalCount };
            query = query.OrderByDescending(x => x.Id);
            int pageSize = dto.PageSize > 0 ? dto.PageSize : 10;
            int page = dto.Page > 0 ? dto.Page : 1;

            result.rows = query
                .Skip((page - 1) * pageSize)
                .Take(pageSize)
                .ToList();

            return result;
        }


        public async Task<WebResponseContent> AddPurchaseReturn(PurchaseReturn entity)
        {
            var result=new WebResponseContent();
            // 可加校验逻辑
             await _purchaseReturnbaseRepository.Add(entity);
            result.OK("添加成功");
            return result;
        }

        public async Task<WebResponseContent> UpdatePurchaseReturn(PurchaseReturn entity)
        {
            var result = new WebResponseContent();

            int rows = await _purchaseReturnbaseRepository.Update(entity);

            if (rows > 0)
            {
                result.OK("修改成功");
            }
            else
            {
                result.Error("修改失败");
            }

            return result;
        }

        /// <summary>
        /// 更新采购退货单状态
        /// </summary>
        /// <param name="id">记录ID</param>
        /// <param name="states">新状态值</param>
        /// <returns>操作结果</returns>
        public async Task<WebResponseContent> UpdatePurchaseReturnStates(int id, int states)
        {
            var result = new WebResponseContent();
            // 查询记录是否存在
            var entity = _purchaseReturnbaseRepository.GetAll().FirstOrDefault(x => x.Id == id);
            if (entity == null)
            {
                return result.Error("记录不存在");
            }
            // 更新状态
            entity.Status = states;
            try
            {
               
                int rows = await _purchaseReturnbaseRepository.Update(entity);

                if (rows > 0)
                {
                    return result.OK("状态更新成功");
                }
                else
                {
                    return result.Error("状态更新失败");
                }
            }
            catch (Exception ex)
            {
                return result.Error($"状态更新异常: {ex.Message}");
            }
        }

        /// <summary>
        /// 批量删除采购退货单
        /// </summary>
        /// <param name="ids">待删除的记录ID数组</param>
        /// <returns>操作结果</returns>
        public async Task<WebResponseContent> BatchDeletePurchaseReturn(int[] ids)
        {
            var result = new WebResponseContent();
            if (ids == null || ids.Length == 0)
            {
                return result.Error("未选择要删除的记录");
            }

            try
            {
                // 查询要删除的记录
                var entities = _purchaseReturnbaseRepository.GetAll().Where(x => ids.Contains(x.Id)).ToList();
                if (entities.Count == 0)
                {
                    return result.Error("未找到要删除的记录");
                }

                

                // 执行批量删除
                int rows = await _purchaseReturnbaseRepository.DeleteAsync(x => ids.Contains(x.Id));

                if (rows > 0)
                {
                    return result.OK($"成功删除{rows}条记录");
                }
                else
                {
                    return result.Error("删除失败");
                }
            }
            catch (Exception ex)
            {
                return result.Error($"删除异常: {ex.Message}");
            }
        }

    }
}
